<template>
  <a-modal v-model:open="open" width="60%" :title="isEdit ? $t('编辑') : $t('New')" @afterClose="handleClose"
    :maskClosable="false">
    <a-spin :spinning="spinning">
      <div class="menus">
        <div class="menus-permission">
          {{ $t("当前菜单") }} {{ currentSelectMenu }}
          <div v-if="currentId">
            <div>
              {{ $t("按钮权限") }}
            </div>
            <a-checkbox-group v-model:value="menuSelected" name="checkboxgroup" :options="menuOptions">
              <template #label="{ labelZh, labelEn, labelAr }">
                <span v-if="isEn">{{ labelEn }}</span>
                <span v-if="isCn">{{ labelZh }}</span>
                <span v-if="isArabic">{{ labelAr }}</span>
              </template>
            </a-checkbox-group>
          </div>
          <div v-else>
            {{ $t("权限分配提示") }}
          </div>
        </div>
        <a-tree v-if="treeData.length" :defaultExpandAll="true" v-model:checkedKeys="checkedKeys" checkStrictly
          @select="chooseKey" checkable :tree-data="treeData" :fieldNames="{
            key: 'id',
          }">
          <template #title="{ nameZh, nameEn, nameAr, id, parentId, path, record }">
            <div style="display: flex; align-items: center"
              @click="setMenuPermission(parentId, id, nameZh, nameEn, nameAr)">
              <span style="font-size: 14px">
                <span v-if="isCn && nameZh">{{ nameZh }}</span>
                <span v-else-if="isArabic && nameAr">{{ nameAr }}</span>
                <span v-else>{{ nameEn }}</span>
              </span>
            </div>
          </template>
        </a-tree>
      </div>

    </a-spin>
    <template #footer>
      <a-button key="back" @click="handleClose">{{ $t("关闭") }}</a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="submit">{{ $t("保存") }}</a-button>
    </template>
  </a-modal>
</template>
<script lang='ts' setup>
import { message } from "ant-design-vue";
import { GenItem, AddItem } from "./item-data";
import {
  queryMenus,
  addRoleMenus,
  GetRoleRouter,
  GetRoleMenus,
} from "@/api/setting";
import { useLanguage } from "@/hooks/index";
import { list2Tree, showCurrentLang } from "@/utils/common/common";
import { permissions } from "@/utils/const";
let spinning = ref(false)
let listData = [];
const { isEn, isCn, isArabic } = useLanguage();
const { t: $t } = useI18n();
const loading = ref(false);
const formRef = ref(null);
const emit = defineEmits(["ok", "close", "update:visible"]);
const menuOptions = permissions;
let currentId = ref(0);
let currentSelectMenu = ref("");
let menuSelected = ref([]);
const spePer = ["viewFlag", "modifyFlag", "removeFlag", "createFlag"];
let totalPermission = reactive({});

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false,
  },
  target: {
    type: Object,
    required: true,
    default: () => {},
  },
});
const open = computed({
  get() {
    return props.visible;
  },
  set(value) {
    emit("update:visible", value);
  },
});
const formState = ref(new GenItem());
const isEdit = computed(() => {
  if (isEmpty(props.target)) return false;
  return true;
});
const treeData = ref([]);
let checkedKeys = ref({
  checked: [],
  halfChecked: []
});
const getRoles = async () => {
  spinning.value = true
  const { data } = await queryMenus().finally(() => {
    spinning.value = false
  })
  // getSecondMenus(data)
  listData = data ?? [];
  treeData.value = list2Tree(data) ?? [];
};

const getRoleRouter = async (id) => {
  spinning.value = true
  const { data } = await GetRoleRouter(id).finally(() => {
    spinning.value = false
  })
  data.forEach((i) => {
    checkedKeys.value.checked.push(i.id);
  });
};
const getRoleMenus = async (id) => {
  spinning.value = true
  const { data } = await GetRoleMenus({ roleId: id }).finally(() => {
    spinning.value = false
  })
  let obj = {};
  data.forEach((i) => {
    if (i.menuId) {
      obj[i.menuId] = i?.otherAuth ?? [];
      if (i.viewFlag) obj[i.menuId].push("viewFlag");
      if (i.modifyFlag) obj[i.menuId].push("modifyFlag");
      if (i.removeFlag) obj[i.menuId].push("removeFlag");
      if (i.createFlag) obj[i.menuId].push("createFlag");
    }
  });
  totalPermission = cloneDeep(obj);
};
//选中节点
const chooseKey = (selectedKeys: any, e: any) => {
  console.log("chooseKey=====>", checkedKeys, e);
};
const setMenuPermission = (parentId, id, nameZh, nameEn, nameAr) => {
  console.log("setMenuPermission:", parentId, id, nameZh, nameEn, nameAr);

  currentSelectMenu.value = isCn.value
    ? nameZh
    : isEn.value
    ? nameEn
    : isArabic.value
    ? nameAr
    : nameEn;
  if (!parentId) {
    currentId.value = 0;
    return;
  }
  // if (!checkedKeys.value.includes(id)) return
  if (id) totalPermission[currentId.value] = cloneDeep(menuSelected.value);
  currentId.value = id;
  menuSelected.value = totalPermission[id];
};
watch(
  () => open,
  (newVal, oldVal) => {
    checkedKeys.value.checked = [];
    totalPermission = {};
    if (newVal.value) {
      getRoles();
      getRoleRouter(props.target.id);
      getRoleMenus(props.target.id);
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

const submit = debounce(async () => {
  if (currentId.value) {
    totalPermission[currentId.value] = menuSelected.value;
  }
  let data = {
    roleId: props.target.id,
    menuList: [],
  };
  let lists = [];
  console.log('sadsad', checkedKeys.value)
  checkedKeys.value.checked.forEach((i) => {
    const target = listData.find((k) => i == k.id);
    const obj = {
      menuId: i,
      viewFlag: false,
      modifyFlag: false,
      removeFlag: false,
      createFlag: false,
      parentId: target.parentId,
      otherAuth: [],
    };
    const perList = totalPermission[i] ?? [];
    if (perList.includes("viewFlag")) obj.viewFlag = true;
    if (perList.includes("modifyFlag")) obj.modifyFlag = true;
    if (perList.includes("removeFlag")) obj.removeFlag = true;
    if (perList.includes("createFlag")) obj.createFlag = true;
    let newPer = perList.filter((item) => {
      return spePer.every((prop) => {
        return prop !== item;
      });
    });
    obj.otherAuth = newPer;
    lists.push(obj);
    if (obj.parentId) {
      const tem = listData.find((ii) => ii.id == obj.parentId);
      const isExit = lists.some((kk) => kk.menuId == tem.id);
      if (!isExit) {
        const obj2 = {
          menuId: tem.id,
          viewFlag: true,
          modifyFlag: true,
          removeFlag: true,
          createFlag: true,
          parentId: 0,
          otherAuth: [],
        };
        lists.push(obj2);
      }
    }
  });
  data.menuList = lists;
  loading.value = true;
  await addRoleMenus(data).finally(() => {
    loading.value = false;
  });
  message.success($t("操作成功"));
  handleOk();
}, 1000);
//
// 自定义业务处理
//
const handleOk = () => {
  emit("ok", (open.value = false));
};
const handleClose = () => {
  emit("update:visible", false);
};
</script>
<style lang='scss' scoped>
.menus {
  display: flex;
  justify-content: space-between;

  :deep(.ant-tree) {
    min-width: 200px;
    max-width: 50%;
    display: flex;
  }
}
</style>